// store/index.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
    state: {
        cart: []
    },
    // 在store.js中
    mutations: {
        ADD_TO_CART(state, cartItem) {
            const found = state.cart.find(item => item.id === cartItem.id);
            if (found) {
                // 如果商品已存在，则更新数量、烹饪方式和配料
                found.quantity += cartItem.quantity;
                found.selectedCookingMethod = cartItem.selectedCookingMethod;
                found.selectedOptions = cartItem.selectedOptions;
            } else {
                // 如果商品不存在，添加到购物车
                state.cart.push({
                    ...cartItem,
                    selectedCookingMethod: cartItem.selectedCookingMethod,
                    selectedOptions: cartItem.selectedOptions
                });
            }
        },
        REMOVE_FROM_CART(state, itemId) {
            const index = state.cart.findIndex(item => item.id === itemId);
            if (index !== -1) {
                state.cart.splice(index, 1); // 从购物车数组中移除指定索引的商品项
            }
        },
        REMOVE_ALL(state){
            state.cart=[];

        }
    },
    // 在store.js中
    actions: {
        addToCart({ commit }, cartItem) {
            commit('ADD_TO_CART', cartItem);
        },
        removeFromCart({ commit }, itemId) {
            commit('REMOVE_FROM_CART', itemId);
        },
        clearCart({commit}){
            commit('REMOVE_ALL')
        }
    },
    getters: {
        cartItems: state => state.cart
    },
});